package authorization_code_postgres

import (
	"fmt"
	"log"
	"net/http"

	"github.com/go-oauth2/oauth2/v4"
	"github.com/go-oauth2/oauth2/v4/errors"
	"github.com/go-oauth2/oauth2/v4/manage"
	"github.com/go-oauth2/oauth2/v4/server"
)

var Oauth2Server *server.Server

func initOauth2Config() {
	clientStore := NewClientStore(db)
	tokenStore := NewTokenStore(db)
	// 创建OAuth2管理器
	manager := manage.NewDefaultManager()
	manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg)

	// 设置存储
	manager.MapClientStorage(clientStore)
	manager.MapTokenStorage(tokenStore)
	// 创建服务器
	Oauth2Server = server.NewDefaultServer(manager)
	Oauth2Server.SetClientInfoHandler(server.ClientFormHandler)

	Oauth2Server.SetInternalErrorHandler(func(err error) (re *errors.Response) {
		log.Println("OAuth 2.0 Error:", err.Error())
		return
	})

	Oauth2Server.SetResponseErrorHandler(func(re *errors.Response) {
		log.Println("Response Error:", re.Error)
	})
	Oauth2Server.SetAllowedGrantType(oauth2.AuthorizationCode, oauth2.PasswordCredentials, oauth2.ClientCredentials, oauth2.Refreshing, oauth2.Implicit)
	Oauth2Server.SetUserAuthorizationHandler(func(w http.ResponseWriter, r *http.Request) (userID string, err error) {
		userID = "userID"
		return
	})
	Oauth2Server.SetAllowGetAccessRequest(false)
	Oauth2Server.SetAuthorizeScopeHandler(func(w http.ResponseWriter, r *http.Request) (scope string, err error) {
		fmt.Println("SetAuthorizeScopeHandler", r.RequestURI)
		scope = "all"
		return
	})

	Oauth2Server.SetClientScopeHandler(func(tgr *oauth2.TokenGenerateRequest) (allowed bool, err error) {
		allowed = true
		return
	})

}

// 令牌验证中间件
func validateToken(r *http.Request, srv *server.Server) error {
	tokenInfo, err := srv.ValidationBearerToken(r)
	if err != nil {
		return err
	}
	fmt.Println("tokenInfo", tokenInfo)
	return nil
}
